﻿using IdentityServer4.Models;
using IdentityServer4.Validation;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace PlatformNetCore.OAuth2
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        // <summary>
        /// 登录用户校验
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            await Task.Run(() =>
            {
                //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
                if (context.UserName == "admin" && context.Password == "123456")
                {
                    List<Claim> claims = new List<Claim>()
                    {
                        new Claim("UserId", context.UserName)
                    };

                    context.Result = new GrantValidationResult(
                     subject: context.UserName,
                     authenticationMethod: "custom",
                     claims: claims);
                }
                else
                {
                    //验证失败
                    context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号密码不正确.");
                }
            });
        }
    }
}
